<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <#include "../../common/header.ftl">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/bootstrap-table.min.css">
    <!-- Latest compiled and minified JavaScript -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/bootstrap-table.min.js"></script>
    <!-- Latest compiled and minified Locales -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/locale/bootstrap-table-zh-CN.min.js"></script>
</head>
<body>
<div class="container-fluid">
    <#include "../../common/left-nav.ftl">

    <div class="main-box">
        <div class="crumbs">
            <ul class="sub-nav">
                <li class="active">账号管理</li>
                <li><a href="${base}/admin/system/role">角色权限</a></li>
                <li><a href="${base}/admin/system/dataset">数据字典</a></li>
            </ul>
        </div>

        <div class="search-bar">
            <input type="text" placeholder="输入账号查询" id="searchBox">
            <a href="javascript:openModal(-1)" class="btn btn-default btn-in-input">
                <span class="glyphicon glyphicon-plus"></span>
            </a>
        </div>
        <div style="padding: 10px">
            <table id="table"></table>
        </div>

    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="dataModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">编辑</h4>
            </div>
            <div class="modal-body">
                <form id="dataForm">
                    <input type="hidden" name="id" id="id">
                    <div class="form-group">
                        <label for="username">账号</label>
                        <input type="text" class="form-control" id="username" placeholder="登录账号">
                    </div>
                    <div class="form-group">
                        <label for="nickname">姓名</label>
                        <input type="text" class="form-control" id="nickname" placeholder="姓名/昵称">
                    </div>
                    <div class="form-group" id="passwordDiv">
                        <label for="password">密码</label>
                        <input type="password" class="form-control" id="password" placeholder="密码">
                    </div>
                    <div class="form-group">
                        <label for="mobilePhone">电话号码</label>
                        <input type="tel" class="form-control" id="mobilePhone" placeholder="密码">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="saveData()">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="pwdModal" tabindex="-1" role="dialog" aria-labelledby="pwdModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="pwdModalLabel">密码</h4>
            </div>
            <div class="modal-body">
                <form id="dataPwdForm">
                    <input type="hidden" id="userId" name="userId">
                    <div class="form-group">
                        <label for="password">新密码</label>
                        <input type="password" class="form-control" name="newPassword" placeholder="输入新设置的密码">
                    </div>
                    <div class="form-group">
                        <label for="password">确认密码</label>
                        <input type="password" class="form-control" name="rPassword" placeholder="重复输入新密码">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="savePwdData()">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="roleModal" tabindex="-1" role="dialog" aria-labelledby="roleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="roleModalLabel">角色</h4>
            </div>
            <div class="modal-body">
                <form id="dataRoleForm">
                    <input type="hidden" name="userId">
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="form-group">
                                <input type="hidden" id="roleUserId">
                                <label for="roleSelectPicker">角色</label>
                                <select multiple class="selectpicker form-control" data-width="300px"
                                        id="roleSelectPicker"></select>
                            </div>
                        </div>

                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="saveRoleData()">保存</button>
            </div>
        </div>
    </div>
</div>
</body>
</html>

<script type="text/javascript">
    var dataTable;
    $(document).ready(function () {
        dataTable = $('#table');
        dataTable.bootstrapTable({
            sidePagination: 'server',
            pagination: true,
            url: API_UCENTER_USER_PAGE,
            ajaxOptions: {
                headers: {
                    access_token: getToken()
                }
            },
            responseHandler: function (res) {
                return {
                    "total": res.total,//总页数
                    "rows": res.list   //数据
                };
            },
            columns: [
                {field: 'id', title: 'ID', visible: false},
                {field: 'username', title: '账号'},
                {field: 'nickname', title: '姓名', width: 200, align: 'center'},
                {field: 'mobilePhone', title: '电话号码', width: 200, align: 'center'},
                {
                    field: 'carrier', title: '编辑', width: 250, align: 'center', formatter: function (value, row) {
                        var enableBtn = '';
                        if (row.status === 'ENABLE') {
                            enableBtn = '<a href="javascript:enableMember(' + row.id + ',false)">禁用</a> | '
                        } else {
                            enableBtn = '<a href="javascript:enableMember(' + row.id + ',true)">启用</a> | '
                        }

                        return '<a href="javascript:openModal(' + row.id + ')">编辑</a> | ' +
                            enableBtn +
                            '<a href="javascript:openRoleModal(' + row.id + ')">权限</a> | ' +
                            '<a href="javascript:openPwdModal(' + row.id + ')">密码</a> | ' +
                            '<a href="javascript:removeData(' + row.id + ')">删除</a>';
                    }
                }
            ]
        });

        $('#searchBox').keypress(function (event) {
            if (event.keyCode === 13) {
                var searchValue = $(this).val();
                dataTable.bootstrapTable("refresh", {
                    query: {
                        username: searchValue
                    }
                })

            }
        });

        var roleSelectPicker = $('#roleSelectPicker');

        $.httpclient.get(API_UCENTER_USER + '/role', {
            time: new Date().getTime()
        }, function (data) {
            data = data.obj;
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    var $option = $('<option></option>');
                    $option.attr('value', item.id);
                    $option.text(item.name);
                    roleSelectPicker.append($option);
                }
                roleSelectPicker.selectpicker('refresh');
            }
        })

    });

    function openModal(userId) {
        var $form = $('#dataForm');
        $form[0].reset();
        if (userId !== null && userId > 0) {
            $('#passwordDiv').hide();
            $('#username').attr("disabled", true);
            $.httpclient.get(API_UCENTER_USER + "/" + userId, null, function (data) {
                for (var field in data) {
                    var $input = $($form.find('input[id=' + field + ']'));
                    $input.val(data[field]);
                }
            })
        } else {
            $('#passwordDiv').show();
            $('#username').removeAttr('disabled');
        }
        $('#dataModal').modal('show');
    }

    function saveData() {
        var $form = $('#dataForm');
        var formData = {};

        $form.find('input').each(function () {
            formData[this.id] = this.value;
        });

        if (formData.id === '' || formData.id === null) {
            $.httpclient.post(API_UCENTER_USER, JSON.stringify(formData), function (data) {
                dataTable.bootstrapTable('refresh');
                $('#dataModal').modal('hide');
            });
        } else {
            $.httpclient.put(API_UCENTER_USER, JSON.stringify(formData), function (data) {
                dataTable.bootstrapTable('refresh');
                $('#dataModal').modal('hide');
            });
        }
    }

    function openPwdModal(id) {
        var $form = $('#dataPwdForm');
        $form[0].reset();
        $('#userId').val(id);
        $('#pwdModal').modal('show');
    }

    function savePwdData() {
        var $form = $('#dataPwdForm');
        var formData = {};

        $form.find('input').each(function () {
            formData[this.name] = this.value;
        });

        if (formData.newPassword === null || formData.newPassword === '') {
            bootbox.alert('请输入新密码');
            return false;
        }

        if (formData.rPassword === null || formData.rPassword === '') {
            bootbox.alert('请输入确认密码');
            return false;
        }

        if (formData.rPassword !== formData.newPassword) {
            bootbox.alert('两次密码不一致');
            return false;
        }

        $.httpclient.post(API_UCENTER_USER + '/pwd', JSON.stringify(formData), function (data) {
            $('#pwdModal').modal('hide');
            bootbox.alert('成功更新密码');
        })
    }

    function removeData(id) {
        bootbox.confirm({
            size: "small",
            message: '是否删除该账户?',
            buttons: {
                confirm: {
                    label: '是',
                    className: 'btn-danger'
                },
                cancel: {
                    label: '否',
                    className: 'btn-success'
                }
            },
            callback: function (result) {
                if (result) {
                    $.httpclient.delete(API_UCENTER_USER + "?id=" + id, {
                        time: new Date().getTime()
                    }, function () {
                        dataTable.bootstrapTable('refresh');
                    });
                }
            }
        });
    }

    function openRoleModal(id) {
        $('#roleUserId').val(id);
        $.httpclient.get(API_UCENTER_USER + '/role?userId=' + id, {
            time: new Date().getTime()
        }, function (data) {
            data = data.obj;
            var roleIds = [];
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                roleIds.push(item.id);
            }
            if (roleIds.length > 0) {
                $('#roleSelectPicker').selectpicker('val', roleIds);
            }

            $('#roleModal').modal('show');
        });
    }

    function saveRoleData() {
        var userId = $('#roleUserId').val();
        var roleIds = $('#roleSelectPicker').selectpicker('val');
        $.httpclient.put(API_UCENTER_USER + '/role', JSON.stringify({
            userId: userId,
            roleIds: roleIds
        }), function (data) {
            $('#roleModal').modal('hide');
            bootbox.alert('成功更新角色数据');
        })
    }

    function enableMember(userId, flag) {
        var message = '';
        if (flag) {
            message = '是否启用账号';
        } else {
            message = '是否禁用账号';
        }

        bootbox.confirm({
            message: message,
            buttons: {
                confirm: {
                    label: '是',
                    className: 'btn-success'
                },
                cancel: {
                    label: '否',
                    className: 'btn-danger'
                }
            },
            callback: function (result) {
                if (result) {
                    $.httpclient.post(API_UCENTER_USER + '/enable', JSON.stringify({
                        userId: userId,
                        flag: flag
                    }), function (data) {
                        if (data.code === 'SUCCESS') {
                            bootbox.alert('操作成功', function () {
                                location.reload();
                            });
                        } else {
                            bootbox.alert(data.message);
                        }

                    });
                }
            }
        });
    }
</script>
